package com.qingxin.sys.action;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.context.ServletContextAware;

import com.qingxin.sys.entity.LoginUser;
import com.qingxin.sys.mvc.SysError;
import com.qingxin.sys.service.SysUserService;
import com.qingxin.sys.support.SystemCfg;

@Controller
public class BaseAction implements ServletContextAware {

	@Autowired
	protected SysUserService sysUserService;
	
	protected ServletContext servletContext;
	
	
	/**
	 * 日志记录对象
	 */
	protected Logger logger = LoggerFactory.getLogger(getClass());
	
	
	@Override
	public void setServletContext(ServletContext servletContext) {
		this.servletContext = servletContext;
	}

	
	/**
	 * 获取登录用户信息，如果用户没有登录返回null
	 * @param request
	 * @return
	 */
	protected LoginUser getLoginUser(HttpServletRequest request){
		String userid = (String) request.getSession().getAttribute(SystemCfg.SESSION_LOGIN_USERID);
		if(userid == null){
			return null;
		}
		LoginUser loginUser = sysUserService.getLoginUser(userid);
		return loginUser;
	}
	
	
	
	protected List<SysError> getSysErrors(BindingResult result){
		List<SysError> list = new ArrayList<SysError>();
		List<ObjectError> errors = result.getAllErrors();
		if(list!=null){
			for(ObjectError error : errors){
				list.add(new SysError(error.getDefaultMessage()));
			}
		}
		return list;
	}
	
}
